import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import config from '../config'
import store from '../store'
import HdThemes from 'iview-layout-themes'

const getToken = HdThemes.util.getToken
Vue.use(Router)
const router = new Router({
    routes,
    mode: 'hash'
})
const LOGIN_PAGE_NAME = 'login'
const WITHOUT_LOGIN_PAGE_NAME = 'withoutCodeLogin'

router.beforeEach((to, from, next) => {
    if (to.name === config.homeName) {
        // 清理面包屑导航数据
        store.dispatch('setBreadCrumb', {list: [], name: 0})
    } else {
        store.dispatch('setBreadCrumb', {list: store.state.app.menuListData, name: null, path: to.path})
    }
    console.log(to)
    const token = getToken()
    if (!token && to.name !== LOGIN_PAGE_NAME && to.name !== WITHOUT_LOGIN_PAGE_NAME) {
        // 未登录且要跳转的页面不是登录页
        next({
            name: LOGIN_PAGE_NAME // 跳转到登录页
        })
    } else if (!token && to.name === LOGIN_PAGE_NAME) {
        // 未登陆且要跳转的页面是登录页
        next() // 跳转
    } else if (!token && to.name === WITHOUT_LOGIN_PAGE_NAME) {
        // 未登陆且要跳转的页面是登录页
        next() // 跳转
    } else if (token && to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        next({
            name: config.homeName // 跳转到homeName页
        })
    }
    next()
})

router.afterEach(to => {
    window.scrollTo(0, 0)
})

export default router
